<?php

namespace App\Admin\Controllers;

use \App\Models\AdminMenu;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Support\Facades\Input;
use Memcache;
use Zofe\Rapyd\DataTree\DataTree;

class MenuController extends Controller
{
    use AdminController;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('菜单管理');
            $content->description('description');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('header');
            $content->description('description');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        if (!class_exists('\Baum\Node')) {
            die("请安装Baum\\Node包");
        }
        //显示菜单列表
        $root = AdminMenu::find(1);
        $grid = '<a href="'.url('admin/system_manage/menu/create').'" class="btn btn-success">添加根目录</a>';
        if($root){
            $grid = DataTree::source($root);
            $grid->add('title');
            $grid->link(url('admin/system_manage/menu/create'), '添加根菜单', 'BR', ['class' => 'btn btn-success']);
        }
        return view('admin.menu', compact('grid'));
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(AdminMenu::class, function (Form $form) {

            $form->display('id', 'ID');
            $pid = Input::get('pid');
            //获取菜单所有菜单节点
            $root = AdminMenu::root();
            $node = $root->getDescendantsAndSelf()->toArray();
            $node = array_column($node, 'title', 'id');

            $form->select('pid', '父节点')->options($node);
            $form->text('title', '菜单标题')->rules('required');
            $form->text('icon', '图标');
            $form->text('url', '路径');
            $form->text('sort', '排序');
            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }
}
